<template>
  <el-container class="water-monitor-layout" fullscreen>
    <!-- 左侧区域-仅显示区域树形结构 -->
    <el-aside width="280px" class="aside-panel">
      <div class="aside-header">
        <el-icon class="header-icon"><LocationFilled /></el-icon>
        <span class="header-title">区域每日流量</span>
      </div>
      <!-- 仅区域树形组件 -->
      <el-tree
          ref="areaTree"
          :data="treeData"
          :props="treeProps"
          :expand-on-click-node="true"
          :filter-node-method="filterTreeNode"
          @node-click="handleNodeSelect"
          class="tree-container"
          v-loading="treeLoading"
          loading-text="加载区域数据中..."
      >
        <!-- 仅保留区域节点图标 -->
        <template #default="{ node }">
          <div class="node-content">
            <el-icon class="node-icon area-icon">
              <OfficeBuilding />
            </el-icon>
            <span class="node-label">{{ node.label }}</span>
          </div>
        </template>
      </el-tree>
    </el-aside>

    <!-- 右侧主内容区 -->
    <el-main class="main-content">
      <!-- 时间筛选栏 -->
      <div class="time-filter-bar">
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
            class="date-picker"
        />
        <el-button-group class="quick-time-group">
          <el-button size="small" type="primary" @click="setQuickTime('today')">今日</el-button>
          <el-button size="small" type="primary" @click="setQuickTime('yesterday')">昨天</el-button>
          <el-button size="small" type="primary" @click="setQuickTime('week')">本周</el-button>
          <el-button size="small" type="primary" @click="setQuickTime('month')">当月</el-button>
          <el-button size="small" type="primary" @click="setQuickTime('lastMonth')">上月</el-button>
        </el-button-group>

        <!-- 新增：导出图表按钮 -->
        <el-button
            size="small"
            type="primary"
            icon="Download"
            @click="handleExportChart"
            class="export-btn"
        >
          导出图表
        </el-button>
        <!-- 基准线控制 -->
        <div class="waterValue-line-control">
          <el-switch
              v-model="showWaterValueLine"
              active-text="显示基准线"
              inactive-text="隐藏基准线"
              class="waterValue-switch"
          />
          <!-- 无基准值时提示 -->
          <span class="waterValue-tip" v-if="!waterValue">（当前区域无基准流量）</span>
        </div>
      </div>

      <!-- 数据展示方式切换标签 -->
      <el-tabs v-model="activeTab" class="data-tabs" style="margin-bottom: 16px;">
        <el-tab-pane label="折线图" name="chart"></el-tab-pane>
        <el-tab-pane label="表格" name="table"></el-tab-pane>
      </el-tabs>

      <!-- 数据展示区域 -->
      <div class="data-container">
        <!-- ECharts区域流量图表 -->
        <div class="chart-container" v-if="activeTab === 'chart'">
          <ECharts
              ref="flowChart"
              :option="chartOption"
              class="chart"
              v-loading="chartLoading"
              loading-text="加载区域每日流量数据中..."
              :events="chartEvents"
          />
          <!-- 无数据提示 -->
          <div class="empty-tip" v-if="!chartLoading && isChartEmpty">
            <el-icon class="empty-icon"><InfoFilled /></el-icon>
            <p class="empty-text">请选择区域并设置日期范围查询每日流量</p>
          </div>
        </div>

        <!-- 区域流量表格 -->
        <div class="table-container" v-if="activeTab === 'table'">
          <el-table
              :data="tableData"
              border
              v-loading="tableLoading"
              loading-text="加载区域每日数据中..."
              style="width: 100%;"
          >
            <el-table-column
                prop="analyseDate"
                label="日期"
                width="200"
                align="center"
            >
              <template #default="scope">
                {{ formatDateTime(scope.row.analyseDate) }}
              </template>
            </el-table-column>
            <el-table-column
                prop="todayWaterVal"
                label="当日流量(吨)"
                align="center"
            />
          </el-table>
          <!-- 表格无数据提示 -->
          <div class="empty-tip" v-if="!tableLoading && tableData.length === 0">
            <el-icon class="empty-icon"><InfoFilled /></el-icon>
            <p class="empty-text">当前日期范围内无区域每日流量数据</p>
          </div>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElButtonGroup, ElButton, ElDatePicker, ElTree, ElIcon, ElTabs, ElTabPane, ElTable, ElTableColumn, ElSwitch } from 'element-plus'
import { Download,LocationFilled, OfficeBuilding, InfoFilled } from '@element-plus/icons-vue'
import ECharts from '@/components/ECharts/index.vue'
import { listArea } from '@/api/water/area'
import { listAreaAnalyse } from '@/api/water/areaAnalyse'
import dayjs from 'dayjs'

// ======================== 响应式数据 ========================
const flowChart = ref(null)
const currentPage = ref(1)
const pageSize = ref(50)
const totalData = ref([])

// 树形结构数据
const treeData = ref([])
const treeProps = ref({
  children: 'children',
  label: 'label'
})
const selectedNode = ref(null)
const dateRange = ref([])

// 加载状态
const treeLoading = ref(false)
const chartLoading = ref(false)
const tableLoading = ref(false)

// 标签页切换
const activeTab = ref('chart')

// 表格数据
const tableData = ref([])

// 基准线控制相关
const showWaterValueLine = ref(true)  // 基准线显示开关
const waterValue = ref(null)          // 当前选中区域的基准值

// ECharts事件配置（监听图例点击事件）
const chartEvents = ref({
  // 图例选中状态变化时触发
  legendselectchanged: (params) => {
    // 仅处理“基准流量线”的图例点击
    if (params.name.includes('基准流量线')) {
      // 同步图例选中状态到基准线开关
      showWaterValueLine.value = params.selected[params.name];
    }
  }
});

// 图表配置
const chartOption = ref({
  // 图例配置（右上角）
  legend: {
    show: true,
    position: 'top-right',
    top: '10px',
    right: '20px',
    itemWidth: 12,
    itemHeight: 12,
    textStyle: {
      fontSize: 12,
      color: '#333'
    },
    data: [
      {
        name: '基准流量线',
        icon: 'line',
        itemStyle: { color: '#f56c6c' }
      }
    ],
    selected: {
      '基准流量线': showWaterValueLine.value
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' },
    formatter: '{b}<br/>当日流量: {c} 吨'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    top: '5%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      formatter: (val) => dayjs(val).format('MM-DD'),
      interval: 0,
      show: true,
      rotate: 45,
    }
  },
  yAxis: {
    type: 'value',
    name: '当日流量 (吨)',
    min: 0,
    splitLine: { show: true, lineStyle: { type: 'dashed' } }
  },
  series: [{
    name: '区域每日流量',
    type: 'line',
    data: [],
    smooth: true,
    itemStyle: { color: '#409eff' },
    lineStyle: { width: 2 },
    // 基准线配置
    markLine: {
      symbol: ['none', 'none'],
      lineStyle: { color: '#f56c6c', type: 'solid', width: 2, opacity: 0.8 },
      data: [{ yAxis: waterValue.value }]
    }
  }]
})

// 图表无数据标识
const isChartEmpty = computed(() => {
  return chartOption.value.series[0].data.length === 0
})

// ======================== 页面初始化 ========================
onMounted(() => {
  initAreaTree()
  setQuickTime('month')
})

// ======================== 区域树形逻辑 ========================
/**
 * 初始化仅区域树形数据
 */
const initAreaTree = async () => {
  treeLoading.value = true
  try {
    const areaRes = await listArea({ pageNum: 1, pageSize: 1000 });
    if (areaRes.code !== 200) throw new Error('获取区域数据失败')

    const areaTree = buildAreaTree(areaRes.rows)
    treeData.value = areaTree

  } catch (err) {
    ElMessage.error(err.message || '区域树形初始化失败')
    console.error('区域树形数据错误：', err)
  } finally {
    treeLoading.value = false
  }
}

/**
 * 构建区域树形结构
 */
const buildAreaTree = (areas) => {
  const areaMap = new Map()
  const rootAreas = []

  areas.forEach(area => {
    areaMap.set(area.id, {
      ...area,
      type: 'area',
      label: area.areaName,
      children: []
    })
  })

  areaMap.forEach(area => {
    const parentId = area.parentAreaId
    if (!parentId || parentId === 0 || !areaMap.has(parentId)) {
      rootAreas.push(area)
    } else {
      const parentArea = areaMap.get(parentId)
      parentArea.children.push(area)
    }
  })

  return rootAreas
}

/**
 * 区域节点选择事件
 */
const handleNodeSelect = (node) => {
  if (node.type === 'area') {
    selectedNode.value = node
    // 从选中的区域节点中获取基准值（使用area.waterValue）
    waterValue.value = node.waterValue !== undefined && node.waterValue !== null
        ? Number(node.waterValue)
        : null
    fetchAreaDailyData()
    // 立即更新基准线
    updateWaterValueMarkLine()
  }
}

// ======================== 时间筛选逻辑 ========================
/**
 * 设置快捷时间范围
 */
const setQuickTime = (type) => {
  let endTime = dayjs().format('YYYY-MM-DD')
  let startTime = ''

  switch (type) {
    case 'today':
      startTime = dayjs().format('YYYY-MM-DD')
      endTime = dayjs().format('YYYY-MM-DD')
      break
    case 'yesterday':
      startTime = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
      endTime = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
      break
    case 'week':
      startTime = dayjs().startOf('week').add(1, 'day').format('YYYY-MM-DD')
      endTime = dayjs().endOf('week').add(1, 'day').format('YYYY-MM-DD')
      break
    case 'month':
      startTime = dayjs().startOf('month').format('YYYY-MM-DD')
      endTime = dayjs().endOf('month').format('YYYY-MM-DD')
      break
    case 'lastMonth':
      startTime = dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD')
      endTime = dayjs().subtract(1, 'month').endOf('month').format('YYYY-MM-DD')
      break
  }

  dateRange.value = [startTime, endTime]
  if (selectedNode.value) fetchAreaDailyData()
}

/**
 * 手动选择时间范围触发
 */
const handleDateChange = () => {
  if (selectedNode.value) fetchAreaDailyData()
}

// ======================== 区域每日流量查询逻辑 ========================
/**
 * 查询区域每日流量数据
 */
const fetchAreaDailyData = async () => {
  if (!selectedNode.value || !dateRange.value[0] || !dateRange.value[1]) {
    ElMessage.warning('请先选择区域并设置日期范围')
    return
  }

  chartLoading.value = true
  tableLoading.value = true
  currentPage.value = 1
  totalData.value = []
  const pageSizeVal = pageSize.value
  let hasMoreData = true

  try {
    while (hasMoreData) {
      const params = {
        areaId: selectedNode.value.id,
        startTime: dateRange.value[0],
        endTime: dateRange.value[1],
        pageNum: currentPage.value,
        pageSize: pageSizeVal
      }

      const res = await listAreaAnalyse(params)
      if (res.code !== 200 || !Array.isArray(res.rows)) {
        throw new Error(`第${currentPage.value}页区域流量数据请求失败，请重试`)
      }

      const currentPageData = res.rows
      totalData.value.push(...currentPageData)

      hasMoreData = currentPageData.length === pageSizeVal
      currentPage.value++
    }

    const sortedData = totalData.value.sort((a, b) => {
      return new Date(a.analyseDate) - new Date(b.analyseDate)
    })

    chartOption.value.xAxis.data = sortedData.map(item => item.analyseDate)
    chartOption.value.series[0].data = sortedData.map(item => item.todayWaterVal)

    tableData.value = sortedData

    if (sortedData.length === 0) {
      ElMessage.info('当前日期范围内无区域每日流量数据')
    }

  } catch (err) {
    ElMessage.error(err.message || '区域每日流量数据查询失败')
    console.error('区域流量分页请求错误：', err)

  } finally {
    chartLoading.value = false
    tableLoading.value = false
    // 数据加载完成后更新基准线
    updateWaterValueMarkLine()
  }
}

/**
 * 格式化日期显示
 */
const formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

/**
 * 更新基准流量线配置 + 动态调整y轴范围 + 同步图例
 */
const updateWaterValueMarkLine = () => {
  if (!chartOption.value || !chartOption.value.series || chartOption.value.series.length === 0) {
    return;
  }

  const targetSeries = chartOption.value.series[0];
  const yAxis = chartOption.value.yAxis;
  const chartData = targetSeries.data;
  const legend = chartOption.value.legend;
  const dataMax = chartData.length > 0
      ? Math.max(...chartData.filter(val => val !== null && !isNaN(val)))
      : 0;

  // 图例动态更新
  let baseLineLegendName = '基准流量线';
  let isBaseLineDisabled = false;

  if (waterValue.value !== null && !isNaN(waterValue.value)) {
    baseLineLegendName = `基准流量线：${waterValue.value.toFixed(2)} 吨`;
    isBaseLineDisabled = false;
  } else {
    baseLineLegendName = '基准流量线（无数据）';
    isBaseLineDisabled = true;
  }

  // 更新图例数据中的基准线项
  const baseLineLegendIndex = legend.data.findIndex(item => item.name.includes('基准流量线'));
  if (baseLineLegendIndex !== -1) {
    legend.data[baseLineLegendIndex] = {
      name: baseLineLegendName,
      icon: 'line',
      itemStyle: { color: '#f56c6c' },
      disabled: isBaseLineDisabled
    };
  }

  // 同步图例选中状态
  legend.selected['基准流量线'] = showWaterValueLine.value && !isBaseLineDisabled;
  legend.selected['区域每日流量'] = true;

  // 基准线和y轴逻辑
  if (showWaterValueLine.value && waterValue.value !== null && !isNaN(waterValue.value) && waterValue.value >= 0) {
    const offset = Math.max(dataMax, waterValue.value) * 0.01 || 0.1;
    yAxis.max = Math.max(dataMax, waterValue.value) + offset;
    yAxis.min = 0;

    // 更新基准线
    targetSeries.markLine = {
      symbol: ['none', 'none'],
      lineStyle: { color: '#f56c6c', type: 'solid', width: 2, opacity: 0.8 },
      data: [{ yAxis: waterValue.value }]
    };
  } else {
    yAxis.max = null;
    yAxis.min = 0;
    targetSeries.markLine = null;
  }

  // 无数据但有基准线时调整y轴
  if (chartData.length === 0 && showWaterValueLine.value && waterValue.value !== null && !isNaN(waterValue.value)) {
    yAxis.max = waterValue.value > 0 ? waterValue.value : 1;
    yAxis.min = 0;
  }

  // 更新图表
  if (flowChart.value) {
    flowChart.value.setOption(chartOption.value, {
      notMerge: false,
      silent: true
    });
  }
};

// 监听基准线开关和基准值变化 → 实时更新图表
watch([showWaterValueLine, waterValue], () => {
  updateWaterValueMarkLine()
}, { immediate: true })

// ======================== 区域树形过滤 ========================
const filterTreeNode = (value, data) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase())
}

// <script setup> 中新增导出方法（建议放在“区域树形过滤”方法之前）
/**
 * 导出区域每日流量图表
 */
const handleExportChart = async () => {
  // 1. 前置校验：确保已选区域和日期范围（适配区域场景，而非水表）
  if (!selectedNode.value) {
    ElMessage.warning('请先选择区域');
    return;
  }
  if (!dateRange.value[0] || !dateRange.value[1]) {
    ElMessage.warning('请设置日期范围');
    return;
  }

  // 2. 获取ECharts子组件实例（复用已定义的 flowChart ref）
  const chartComponent = flowChart.value;
  if (!chartComponent) {
    ElMessage.error('图表组件未加载，请稍后重试');
    return;
  }

  // 3. 获取ECharts核心实例（依赖子组件暴露的 getEchartsInstance 方法）
  const echartsInstance = chartComponent.getEchartsInstance();
  if (!echartsInstance) {
    ElMessage.error('ECharts实例未初始化，请稍后重试');
    return;
  }

  try {
    // 4. 保存原始图表标题（用于下载后恢复）
    const originalTitle = chartOption.value.title || null;

    // 5. 临时添加图表标题（包含区域名、数据类型、日期范围，适配区域场景）
    const areaName = selectedNode.value.label; // 区域名（替换之前的水表名）
    const timeRangeText = `${dayjs(dateRange.value[0]).format('YYYY-MM-DD')} 至 ${dayjs(dateRange.value[1]).format('YYYY-MM-DD')}`;
    chartOption.value.title = {
      text: `区域：${areaName} | 每日流量 | 时间范围：${timeRangeText}`,
      left: 'center',
      textStyle: { fontSize: 14, fontWeight: 'normal' }
    };

    // 6. 触发图表更新，确保标题渲染
    chartComponent.setOption(chartOption.value);

    // 7. 延迟导出（等待标题渲染完成，避免图片缺漏）
    setTimeout(() => {
      // 生成高清PNG图片（白色背景避免透明底文字模糊，pixelRatio:2保证清晰度）
      const imgBase64 = echartsInstance.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#ffffff'
      });

      // 8. 构建下载链接，文件名适配区域场景
      const link = document.createElement('a');
      link.href = imgBase64;
      // 文件名格式：区域名_数据类型_开始日期_结束日期.png（便于归档）
      const fileName = `${areaName}_区域每日流量_${dayjs(dateRange.value[0]).format('YYYYMMDD')}_${dayjs(dateRange.value[1]).format('YYYYMMDD')}.png`;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      // 9. 恢复原始标题，避免影响后续图表显示
      chartOption.value.title = originalTitle;
      chartComponent.setOption(chartOption.value);

      ElMessage.success('图表导出成功');
    }, 100);

  } catch (error) {
    ElMessage.error(`导出失败：${error.message}`);
    console.error('区域每日流量图表导出错误：', error);
  }
};
</script>

<style scoped>
.water-monitor-layout {
  display: flex;
  height: calc(100vh - 84px);
  overflow: hidden;
}

.aside-panel {
  height: 100%;
  background-color: #f8f9fa;
  border-right: 1px solid #e9ecef;
}

.aside-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e9ecef;
}

.header-icon {
  color: #409eff;
  font-size: 18px;
}

.header-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.tree-container {
  height: calc(100% - 84px);
  overflow-y: auto;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-icon {
  font-size: 14px;
}

.area-icon {
  color: #409eff;
}

.main-content {
  padding: 20px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.time-filter-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.date-picker {
  width: 360px;
}

.quick-time-group {
  display: flex;
  gap: 8px;
}

/* 基准线开关样式 */
.waterValue-line-control {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto;
}

.waterValue-switch {
  --el-switch-on-color: #409eff;
  --el-switch-off-color: #e5e7eb;
}

.waterValue-tip {
  font-size: 12px;
  color: #909399;
}

/* 适配小屏幕 */
@media (max-width: 1200px) {
  .time-filter-bar {
    gap: 12px;
  }
  .waterValue-line-control {
    margin-left: 0;
    margin-top: 8px;
    width: 100%;
    justify-content: flex-start;
  }
}

.data-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chart-container {
  position: relative;
  height: 100%;
  width: 100%;
}

.chart {
  width: 100%;
  height: 100%;
}

.table-container {
  position: relative;
  height: 100%;
  width: 100%;
  overflow: auto;
}

.empty-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.empty-icon {
  font-size: 32px;
  margin-bottom: 8px;
}
</style>